<?php

namespace Portal\Domain;

use Portal\Model\Log as LogModel;

class Log
{
    public function insertLog($response)
    {
        // $response = \PhalApi\DI()->response->getResult();
        $endTime = microtime(true);
        $executionTime = $this->getTime($endTime);
        // $executionTime = $endTime - START_TIME;
        $insert['ip'] = \PhalApi\Tool::getClientIp();
        $insert['request_method'] = $_SERVER['REQUEST_METHOD'];
        $insert['request_params'] = $this->getAllInput();
        $insert['response_content'] = json_encode($response);
        $insert['content'] = json_encode($response);
        $insert['request_uri'] = $_SERVER['REQUEST_URI'];
        $insert['module'] = \PhalApi\DI()->request->getService();
        $insert['method'] = $_SERVER['REQUEST_METHOD'];
        $insert['execution_time'] = $executionTime;
        $insert['browser'] = $_SERVER['HTTP_USER_AGENT'];
        $insert['os'] =  $_SERVER['HTTP_USER_AGENT'];
        $insert['create_by'] = intval(\PhalApi\DI()->admin->getId());
        $insert['create_time'] = time();
        $locationStr = $this->getIpLocation($insert['ip']);
        $insert['province'] = $locationStr;
        $insert['city'] = $locationStr;
        LogModel::notorm()->insert($insert);
    }

    private function getAllInput()
    {
        $input = file_get_contents('php://input');

        if ($_SERVER['CONTENT_TYPE'] === 'application/json') {
            return json_decode($input, true) ?? [];
        }

        parse_str($input, $data);
        return json_encode(array_merge($_GET, $_POST, $data ?? []));
    }

    public function getIpLocation($ip)
    {

        if (trim($ip) == '' || strpos($ip, '10.') === 0 || strpos($ip, '192.') === 0 || strpos($ip, '172.') === 0 || $ip == 'localhost') {
            return '本地';
        }
        $url = "https://opendata.baidu.com/api.php?query=$ip&co=&resource_id=6006&oe=utf8";
        $curl = new \Curl\Curl();
        $curl->setConnectTimeout(1);
        $curl->setTimeout(1);
        $responseData = $curl->get($url);
        if (is_object($responseData) && $responseData->status == "0") {
            if (isset($responseData->data[0]->location)) {

                return   $responseData->data[0]->location;
            }
        }

        return "未知";
    }

    private function getTime($endTime)
    {
        list($startUsec, $startSec) = explode(" ", START_TIME);
        $startTime = (float)$startSec + (float)$startUsec;

        list($endUsec, $endSec) = explode(" ", $endTime);
        $endTime = (float)$endSec + (float)$endUsec;
        $time_diff = ($endTime - $startTime) * 1000; // 将秒转换为毫秒
        return $time_diff;
    }
}
